package org.hyn.gateway.socket.handlers;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import org.hyn.gateway.bind.IGenericReference;
import org.hyn.gateway.executor.result.SessionResult;
import org.hyn.gateway.session.GatewaySession;
import org.hyn.gateway.session.defaults.DefaultGatewaySessionFactory;
import org.hyn.gateway.socket.BaseHandler;
import org.hyn.gateway.socket.agreement.AgreementConstants;
import org.hyn.gateway.socket.agreement.GatewayResultMessage;
import org.hyn.gateway.socket.agreement.RequestParser;
import org.hyn.gateway.socket.agreement.ResponseParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @author franyhu
 * @description 协议数据处理
 * @date 2025/3/17
 */
public class ProtocolDataHandler extends BaseHandler<FullHttpRequest> {

    private final Logger logger = LoggerFactory.getLogger(ProtocolDataHandler.class);

    private final DefaultGatewaySessionFactory gatewaySessionFactory;

    public ProtocolDataHandler(DefaultGatewaySessionFactory gatewaySessionFactory) {
        this.gatewaySessionFactory = gatewaySessionFactory;
    }

    @Override
    protected void session(ChannelHandlerContext ctx, Channel channel, FullHttpRequest request) {
        logger.info("网关接受请求【消息处理】 uri:{} method:{}", request.uri(), request.method());

        try {
            // 1.解析请求参数
            RequestParser requestParser = new RequestParser(request);
            String uri = requestParser.getUri();
            if (uri == null) {
                return;
            }
            Map<String, Object> params = requestParser.parse();

            // 2.调用会话服务 - 服务泛化调用
            GatewaySession gatewaySession = gatewaySessionFactory.openSession(uri);
            IGenericReference reference = gatewaySession.getMapper();
            SessionResult result = reference.$invoke(params);

            // 3.封装返回结果
            DefaultFullHttpResponse response = new ResponseParser().parse(
                    "0000".equals(result.getCode()) ? GatewayResultMessage.buildSuccess(result.getData())
                            : GatewayResultMessage.buildError(AgreementConstants.ResponseCode._404.getCode(), "网关协议调用失败")
            );
            channel.writeAndFlush(response);
        } catch (Exception e) {
            // 4.发生异常，封装返回结果
            DefaultFullHttpResponse response = new ResponseParser().parse(
                    GatewayResultMessage.buildError(AgreementConstants.ResponseCode._502.getCode(), "网关协议调用失败 " + e.getMessage())
            );
            channel.writeAndFlush(response);
        }
    }
}
